package codeTop;

import java.util.ArrayList;
import java.util.List;

public class q113 {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return res;
        }
        dfs(root,targetSum,res,list);
        return res;
    }

    private void dfs(TreeNode node, int targetSum, List<List<Integer>> res, List<Integer> list) {
        if (node.left == null && node.right==null) {
            if (targetSum == node.val) {
                list.add(node.val);
                res.add(List.copyOf(list));
                list.remove(list.size()-1);
            }
            return;
        }
        list.add(node.val);
        if (node.left != null) {
            dfs(node.left,targetSum- node.val,res,list);
        }
        if (node.right != null) {
            dfs(node.right,targetSum- node.val,res,list);
        }
        list.remove(list.size()-1);
    }
}
